package javbot.mail;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.util.ArrayList;

public class MailReader {

	String mailServer;
	String user;
	String password;
	boolean deletedMail;
	
	public MailReader(String mailServer, String user, String password) {
		this.mailServer = mailServer;
		this.user = user;
		this.password = password;
	}
	
	public String[] getMail() {
		
		ArrayList<String> msgs = new ArrayList<String>();
		int totalMsgs = 0;
		
		try {
			Socket s = new Socket(mailServer, 110);
			BufferedReader in = new BufferedReader(new InputStreamReader(s
					.getInputStream()));
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s
					.getOutputStream()));

			
			loginMail(in, out, user, password);
			totalMsgs = getNumberOfMessages(in, out);
			if (totalMsgs == 0) {
				System.out.println("No mail waiting.");
			} else {
				for (int i = 1; i <= totalMsgs; i++) {
					String mail = getMail(in, out, i);
					if (mail != null)
						msgs.add(mail);
				}

				if (deletedMail) {
					// If the mail was removed from the server 
					// then we must COMMIT with the "QUIT" command
					send(out, "QUIT");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return msgs.toArray(new String[totalMsgs]);
	}


	private String getMail(BufferedReader in, BufferedWriter out, int mailNumber)
			throws IOException {
		String line = "";
		String mailContent = "";
		send(out, "RETR " + mailNumber);
		while (((line = in.readLine()) != null) && (!(line.equals("."))))
			mailContent += line + "\n";
		if (MailParser.isJavbotMail(mailContent)) {
			send(out, "DELE " + mailNumber);
			receive(in);
			deletedMail = true;
		}

		return mailContent;
	}

	private void send(BufferedWriter out, String s) throws IOException {
		out.write(s + "\n");
		out.flush();
	}

	private String receive(BufferedReader in) throws IOException {
		return in.readLine();
	}

	private void loginMail(BufferedReader in, BufferedWriter out, String user,
			String pass) throws IOException {
		receive(in);
		send(out, "USER " + user);
		receive(in);
		send(out, "PASS " + pass);
		receive(in);
	}

	private int getNumberOfMessages(BufferedReader in, BufferedWriter out)
			throws IOException {
		int i = 0;
		String s;

		send(out, "LIST");
		receive(in);
		while ((s = receive(in)) != null) {
			if (!(s.equals("."))) {
				i++;
			} else
				return i;
		}
		return 0;
	}
}
